package com.filter;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.filter.OncePerRequestFilter;

import com.utils.JdbcUtils;
import com.utils.ObjectUtils;
import com.utils.Ret;

/**
 * 登录过滤
 * 
 * @author geloin
 * @date 2012-4-10 下午2:37:38
 */
public class SessionFilter extends OncePerRequestFilter {

	@Override
	protected void doFilterInternal(HttpServletRequest request,
			HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {
		// 不过滤的uri
		String[] notFilter = new String[] { "/login.do", "/captcha.do",
				"/userlogin.do", "/getPomrInfoByUcode.do", "/userlogin.jsp",
				"/login.jsp", "getJmtjInfoByUcode.do","getFamilyInfoByUcode.do","doRegist.do" };
		// 请求的uri
		String uri = request.getRequestURI();
		// uri中包含background时才进行过滤
		if (uri.indexOf("do") != -1 || uri.indexOf("jsp") != -1) {
			// 是否过滤
			boolean doFilter = true;
			for (String s : notFilter) {
				if (uri.indexOf(s) != -1) {
					// 如果uri中包含不过滤的uri，则不进行过滤
					doFilter = false; ;
				}
			}
			if (doFilter) {
				// 执行过滤
				// 从session中获取登录者实体
				Object obj = request.getSession().getAttribute("usercode");
				if (null == obj) {
					// 如果session中不存在登录者实体，则弹出框提示重新登录
					// 设置request和response的字符集，防止乱码
					request.setCharacterEncoding("UTF-8");
					response.setCharacterEncoding("UTF-8");

					request.getRequestDispatcher("login.jsp").forward(request,
							response);
				} else {
					// 判断角色是否有该访问路径
					if (hasAuth(uri, request)) {
						filterChain.doFilter(request, response);
					} else {
						Ret ret = new Ret();
						ret.setStatusCode("500");
						ret.setMessage("无权限！");
						ret.setNavTabId("");
						
						PrintWriter out = null;
						try {
							out = response.getWriter();
						} catch (IOException e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						}
						
						out.print(ret.toJsonString());
						out.flush();
						out.close();
					}
				}
			} else {
				// 如果不执行过滤，则继续
				filterChain.doFilter(request, response);
			}
		} else {
			// 如果uri中不包含do，则继续
			filterChain.doFilter(request, response);
		}
	}

	// 判断是否有权限
	Boolean hasAuth(String uri, HttpServletRequest request) {

		Boolean hasAuth = false;
		HttpSession session = request.getSession();
		int type = ObjectUtils.getIntVal(session.getAttribute("usertype")
				.toString());

		JdbcUtils dbHelper = new JdbcUtils();

		ResultSet resultSet = dbHelper
				.executeResultSet("SELECT * FROM USER_AUTH where type=" + type);

		try {

			if (null != resultSet) {
				while (resultSet.next()) {
					String auth = resultSet.getString("path");
					if (uri.indexOf(auth) != -1) {
						hasAuth = true;
						break;
					}
				}
			} else {
				hasAuth = false;
			}

		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			dbHelper.close();
		}
		
		return hasAuth;
	}
	
	private String getServicePath(HttpServletRequest request){
	    String path = request.getContextPath();
	    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
	    return basePath;
	}
	
	private Boolean sessionCheck(HttpServletRequest request){
		
		
		return true;
	}
}
